unit UFrameClient;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 
  Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
  cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxTextEdit,
  cxMaskEdit, cxButtonEdit;

type
  TFrameClient = class(TFrame)
    edtClient: TcxButtonEdit;
    procedure edtClientExit(Sender: TObject);
    procedure edtClientPropertiesButtonClick(Sender: TObject;
      AButtonIndex: Integer);
    procedure edtClientKeyPress(Sender: TObject; var Key: Char);
  private
    procedure ShowClientSelect(ClearFilter: Boolean);
    procedure SetNullData;
    procedure SetSelectData;
  public
    gClientGuid: string;
  end;

implementation

uses UDmBillBase, UFrmClientSelect;

{$R *.dfm}

procedure TFrameClient.SetNullData;
begin
  gClientGuid := '';
  edtClient.Text := '';
end;

procedure TFrameClient.SetSelectData;
begin
  gClientGuid := DmBillBase.CdsClient.FindField('Guid').AsString;
  edtClient.Text := DmBillBase.CdsClient.FindField('ClientName').AsString;
end;

procedure TFrameClient.edtClientExit(Sender: TObject);
var
  lClient: string;
begin
  lClient := Trim(edtClient.Text);
  if lClient = '' then
  begin
    SetNullData;
    Exit;
  end;
  DmBillBase.DoClientFilter(lClient);
  if DmBillBase.CdsClient.RecordCount = 1 then
  begin
    SetSelectData;
  end
  else
  if DmBillBase.CdsClient.RecordCount > 1 then
  begin
    ShowClientSelect(False);
  end
  else
  begin
    SetNullData;
  end;
  DmBillBase.CdsClient.Filtered := False;
  DmBillBase.CdsClient.Filter := '';
end;

procedure TFrameClient.edtClientKeyPress(Sender: TObject; var Key: Char);
var
  lClient: string;
begin
  if Key = #13 then
  begin
    lClient := Trim(edtClient.Text);
    if lClient = '' then
      ShowClientSelect(True)
    else
      edtClientExit(Sender);
  end;
end;

procedure TFrameClient.edtClientPropertiesButtonClick(Sender: TObject;
  AButtonIndex: Integer);
begin
  ShowClientSelect(True);
end;

procedure TFrameClient.ShowClientSelect(ClearFilter: Boolean);
begin
  if ClearFilter then
  begin
    DmBillBase.CdsClient.Filtered := False;
    DmBillBase.CdsClient.Filter := '';
  end;
  FrmClientSelect := TFrmClientSelect.Create(nil);
  try
    if FrmClientSelect.ShowModal = mrOk then
    begin
      SetSelectData;
    end
    else
    begin
      SetNullData;
    end;
  finally
    FreeAndNil(FrmClientSelect);
  end;
end;

end.
